<template>
  <el-dialog
    title="添加类别"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :show-close="false"
    width="400px"
    @closed="onDialogClosed"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="类别名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入类别名称"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
export default {
  name: 'AddCategoryDialog',
  props: {
    visible: Boolean,
    parentId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '类别名称不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '长度应为 2 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleCancel() {
      this.$emit('update:visible', false)
    },
    handleConfirm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.$emit('submit', {
            name: this.form.name,
            parentId: this.parentId
          })
          this.$emit('update:visible', false)
        }
      })
    },
    onDialogClosed() {
      this.resetForm()
    },
    resetForm() {
      this.form.name = ''
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate()
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
